package com.yupi.yuoj.judge;

import cn.hutool.json.JSONUtil;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.judge.codesandbox.CodeSandbox;
import com.yupi.yuoj.judge.codesandbox.CodeSandboxFactory;
import com.yupi.yuoj.judge.codesandbox.CodeSandboxProxy;
import com.yupi.yuoj.judge.codesandbox.model.ExecuteCodeRequest;
import com.yupi.yuoj.judge.codesandbox.model.ExecuteCodeResponse;
import com.yupi.yuoj.judge.strategy.DefaultJudgeStrategy;
import com.yupi.yuoj.judge.strategy.JudgeContext;
import com.yupi.yuoj.model.dto.question.JudgeCase;
import com.yupi.yuoj.judge.codesandbox.model.JudgeInfo;
import com.yupi.yuoj.model.dto.question.JudgeConfig;
import com.yupi.yuoj.model.entity.Question;
import com.yupi.yuoj.model.entity.QuestionSubmit;
import com.yupi.yuoj.model.enums.JudgeInfoMessageEnum;
import com.yupi.yuoj.model.enums.QuestionSubmitLanguageEnum;
import com.yupi.yuoj.model.enums.QuestionSubmitStatusEnum;
import com.yupi.yuoj.service.QuestionService;
import com.yupi.yuoj.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class JudgeServiceImpl implements JudgeService {

    @Value("${codesandbox.type : example}")
    private String type;

    @Resource
    private JudgeManager judgeManager;

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionSubmitService questionSubmitService;
    @Override
    public QuestionSubmit doJudge(Long questionSubmitId) { // 对提交的题目进行判题 ， 根据提交编号查询到提交的题目
        //根据传来的id获取questionSubmit
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if(questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR , "提交信息不存在！");
        }

        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);

        if(question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR , "题目不存在！");
        }
        //如果正在执行，就显示正在运行
        if(questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR , "题目正在运行！");
        }

        //将题目的状态更新为运行中
        //设置一个更新后的questionSubmit对象
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());

        boolean update = questionSubmitService.updateById(questionSubmitUpdate);

        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR , "题目状态更新失败！");
        }

        //注册一个type类型的代码沙箱 !!!
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        codeSandbox = new CodeSandboxProxy(codeSandbox);

//        String language = QuestionSubmitLanguageEnum.jAVA.getValue();
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        String judgeCaseStr = question.getJudgeCase();

        //!!!
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr , JudgeCase.class);

        //!!!
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());

        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();

        //----------------------------------------------------------------------------------------------------------execute
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);


        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(executeCodeResponse.getOutputList());
        judgeContext.setQuestionSubmit(questionSubmit);
        judgeContext.setQuestion(question);

        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);

        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));

        boolean updateResult = questionSubmitService.updateById(questionSubmitUpdate);

        if(!updateResult){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR , "题目状态更新失败！");
        }


        //将更新后的questionSubmit返回给前端
        return questionSubmitService.getById(questionSubmitId);

    }
}
